package com.yhq.thrift.server;

import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.TProcessor;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by yhq on 2016/12/2.
 */
@Slf4j
public class DefaultThriftServer {

    private int serverPort;

    private List<TProcessor> processorList;

    private static TServer server;

    public void run (){
        if(serverPort == 0){
            log.error("服务启动失败：serverPort未配置");
            return;
        }

        TMultiplexedProcessor processor = new TMultiplexedProcessor();

        for (TProcessor tProcessor : processorList) {
            String serviceName = tProcessor.getClass().getName();
            log.info("注册服务：{}",serviceName);
            processor.registerProcessor(serviceName, tProcessor);
        }

        try {
            TServerTransport transport = new TServerSocket(serverPort);
            server = new TThreadPoolServer(new TThreadPoolServer.Args(transport).processor(processor));
            server.serve();
        }catch (TTransportException tt){
            log.error("服务启动失败",tt);
        }
    }

    public void stop(){
        if(server != null && server.isServing()){
            server.stop();
        }
    }

    public int getServerPort() {
        return serverPort;
    }

    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }

    public List<TProcessor> getProcessorList() {
        return processorList;
    }

    public void setProcessorList(List<TProcessor> processorList) {
        this.processorList = processorList;
    }
}
